<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="6">
            <a-form-model-item label="单据编码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" disabled placeholder="系统自动生成"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="审批流程" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="approvalFlow">
              <j-dict-select-tag
                type="list"
                v-model="model.approvalFlow"
                dictCode="sample_pick_bill_flow"
                placeholder="请选择审批流程"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="客户" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customerId">
              <j-dict-select-tag
                type="list"
                dictCode="erp_customer,name,id"
                v-model="model.customerId"
                placeholder="请选择客户"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="6">
            <a-form-model-item label="入库仓库" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="wareNo">
              <a-select v-model="model.wareNo" placeholder="请选择入库仓库" style="width: 100%">
                <a-select-option v-for="item in houselist" :key="item.warehouseCode" :value="item.warehouseCode">
                  {{ item.warehouseName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="领料人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="pickBy">
              <a-row :gutter="4">
                <a-col :span="18">
                  <a-input v-model="model.pickBy" placeholder="请选择领料人"></a-input>
                </a-col>
                <a-col :span="6">
                  <a-button @click="handleSelectEmployee" type="primary" :loading="confirmLoading">选择</a-button>
                </a-col>
              </a-row>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="领料部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="pickOrgName">
              <a-input v-model="model.pickOrgName" placeholder="" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="领料日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="pickDate">
              <j-date
                placeholder="请选择领料日期"
                v-model="model.pickDate"
                :show-time="true"
                date-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item
              label="备注"
              :labelCol="{ xs: { span: 24 }, sm: { span: 1 } }"
              :wrapperCol="{ xs: { span: 24 }, sm: { span: 22 } }"
              prop="remark"
            >
              <a-input v-model="model.remark" placeholder="请输入备注"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="领料明细" :key="refKeys[0]" :forceRender="true">
        <a-row :gutter="20" style="margin-bottom: 5px">
          <a-col :span="2">
            <a-button @click="addMaterial" :disabled="formDisabled">新增物料</a-button>
          </a-col>
        </a-row>
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="tslSamplePickBillDetailTable.loading"
          :columns="tslSamplePickBillDetailTable.columns"
          :dataSource="tslSamplePickBillDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="false"
        >
          <template v-slot:action="{ row }">
            <a-popconfirm title="确认删除?" @confirm="() => handleRemove(row)" :disabled="formDisabled">
              <a href="javascript:;" :disabled="formDisabled">删除</a>
            </a-popconfirm>
          </template>
        </j-vxe-table>
      </a-tab-pane>
    </a-tabs>
    <select-pick-user-modal ref="selectPickUserModal" @handlerOk="handleSelectEmployeeOk" />
    <material-inventory
      ref="materialInventory"
      @goodRowsOk="goodsOk"
      checkval="checkbox">
    </material-inventory>
  </a-spin>
</template>

<script>
import { getAction, postAction } from '@/api/manage'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import store from '@/store'
import EmployeeListModal from '@/components/tsl/modules/EmployeeListModal.vue'
import { getDate } from '@/utils'
import ErpAllGoodsListModal from '@/components/base/modal/ErpAllGoodsListModal.vue'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'
import SelectPickUserModal from '../SelectPickUserModal.vue'
import MaterialInventory from './MaterialInventory.vue'

export default {
  name: 'TslSamplePickBillForm',
  mixins: [JVxeTableModelMixin],
  components: {
    JFormContainer,
    EmployeeListModal,
    ErpAllGoodsListModal,
    SelectPickUserModal,
    MaterialInventory,
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      model: { orgCode: store.getters.userInfo.orgCode },
      houselist: [],
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {
        approvalFlow: [{ required: true, message: '请输入审批流程!' }],
        pickBy: [{ required: true, message: '请输入领料人!' }],
        pickDate: [{ required: true, message: '请输入领料日期!' }],
      },
      refKeys: ['tslSamplePickBillDetail'],
      tableKeys: ['tslSamplePickBillDetail'],
      activeKey: 'tslSamplePickBillDetail',
      // 样品领料单子表
      tslSamplePickBillDetailTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '客户物料编码',
            key: 'customCode',
            type: JVXETypes.normal,
            minWidth: '140px',
            defaultValue: '',
          },
          {
            title: '物料编码',
            key: 'productCode',
            type: JVXETypes.normal,
            minWidth: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '物料名称',
            key: 'productBatchNo',
            type: JVXETypes.normal,
            minWidth: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '规格型号',
            key: 'materialSpec',
            type: JVXETypes.normal,
            minWidth: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '主单位',
            key: 'meUnit',
            type: JVXETypes.select,
            dictCode: 'ji_unit',
            minWidth: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '库存可用数量',
            key: 'stockQuantity',
            dataIndex: 'stockQuantity',
            defaultValue: '0',
            minWidth: 120,
          },
          {
            title: '申请数量',
            key: 'applyQuantity',
            type: JVXETypes.input,
            minWidth: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [
              { required: true, message: '${title}不能为空' },
              {
                // 自定义函数校验 handler
                handler({ cellValue, row, column }, callback, target) {
                  // cellValue 当前校验的值
                  // row 当前行数据
                  // column 当前列配置
                  // callback(flag, message) 方法【必须执行】且只能执行一次。
                  //          flag = 是否通过了校验，不填写或者填写 null 代表不进行任何操作
                  //          message = 提示的类型，默认使用配置的 message
                  // target 行编辑的实例对象

                  // 示例：
                  if (cellValue <= 0) {
                    callback(false, '${title}不能小于0') // false = 未通过，可以跟自定义提示
                  } else {
                    callback(true) // true = 通过验证
                  }
                },
                message: '${title}必须为正数',
              },
            ],
          },
          {
            title: '备注',
            key: 'remark',
            type: JVXETypes.input,
            minWidth: '300px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '操作',
            key: 'action',
            type: JVXETypes.slot,
            fixed: 'right',
            minWidth: '100px',
            align: 'center',
            slotName: 'action',
          },
        ],
      },
      url: {
        add: '/pro/tslSamplePickBill/add',
        edit: '/pro/tslSamplePickBill/edit',
        queryById: '/pro/tslSamplePickBill/queryById',
        warehouseList: '/wms/basic/warehouse/list',
        tslSamplePickBillDetail: {
          list: '/pro/tslSamplePickBill/queryTslSamplePickBillDetailByMainId',
        },
      },
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    customFormData: {
      type: Object,
      default: () => {
        return {}
      },
      required: false,
    },
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    getAction(this.url.warehouseList, { pageSize: 999, pageNo: 1, warehouseType: 8 }).then((res) => {
      if (res.success) {
        this.houselist = res.result.records
        if (this.houselist != null && this.houselist.length > 0) {
          this.houselist.forEach((item) => {
            if (item.sysOrgCode == store.getters.userInfo.orgCode && !this.model.wareNo) {
              this.model.wareNo = item.warehouseCode
            }
          })
        }
      }
    })
    if (this.customFormData != null && this.customFormData.id) {
      this.edit(this.customFormData)
    }
  },
  methods: {
    addMaterial() {
      this.$refs.materialInventory.add()
    },
    handleRemove(key) {
      const dataSource = [...this.tslSamplePickBillDetailTable.dataSource]
      this.tslSamplePickBillDetailTable.dataSource = dataSource.filter((item) => item.id !== key.id)
    },
    goodsOk(datas) {
      const that = this
      const ids = that.tslSamplePickBillDetailTable.dataSource.map((item) => item.materialId)
      if (datas && datas.length > 0) {
        datas.forEach((item) => {
          if (ids.indexOf(item.id) < 0) {
            let detail = {}
            detail.customCode = item.customerMaterialCode
            detail.productCode = item.materialCode
            detail.productBatchNo = item.materialName
            detail.materialSpec = item.specificationModel
            detail.meUnit = item.unit
            detail.stockQuantity = item.quantity
            detail.remark = ''
            detail.applyQuantity = ''
            that.tslSamplePickBillDetailTable.dataSource.push(detail)
          }
        })
      }
    },
    //选择员工方法
    handleSelectEmployeeOk(data) {
      if (data) {
        this.model.pickBy = data.realname
        this.model.pickOrgCode = data.orgCode
        this.model.pickOrgName = data.orgCodeTxt
        this.$forceUpdate() //重新渲染UI
      }
    },
    //绑定所属员工
    handleSelectEmployee() {
      this.$refs.selectPickUserModal.visible = true
    },
    add() {
      this.tslSamplePickBillDetailTable.dataSource = []
    },
    edit(record) {
      this.model = record
      this.model.pickOrgName = this.model.pickOrgCode_dictText
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(this.url.tslSamplePickBillDetail.list, params, this.tslSamplePickBillDetailTable)
      }
    },
    async handleOk() {
      //  校验主表单
      const mainFormValid = await new Promise((resolve) => {
        this.$refs.form.validate((valid) => resolve(valid))
      })
      if (!mainFormValid) return

      let hasMissingFields = false
      this.tslSamplePickBillDetailTable.dataSource.forEach((row, index) => {
        if (!row.applyQuantity || row.applyQuantity === '') {
          hasMissingFields = true
          this.$message.error(`第 ${index + 1} 行的申请数量不能为空`)
        } else if (row.applyQuantity > (Number(row.stockQuantity) || 0)) {
          hasMissingFields = true
          this.$message.error(`第 ${index + 1} 行的申请数量不能大于库存可用数量`)
        }
      })
      if (hasMissingFields) return
      //  调用接口提交（根据实际接口调整）
      this.confirmLoading = true
      this.model.approveType = this.model.approvalFlow
      this.model.tslSamplePickBillDetailList = this.tslSamplePickBillDetailTable.dataSource
      try {
        const url = this.model.code ? this.url.edit : this.url.add // 编辑/新增判断
        await postAction(url, this.model)
        this.$message.success('提交成功')
        this.$emit('ok') // 触发提交成功事件，通知模态框
      } catch (error) {
        this.$message.error('提交失败：' + (error.message || '网络异常'))
      } finally {
        this.confirmLoading = false
      }
    },
  },
}
</script>

<style scoped></style>
